import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

const API_URL = 'http://localhost:3000/api'

export interface UserInfo {
  id: string
  username: string
  email: string
  avatar?: string
  role: 'user' | 'admin'
}

export interface LoginForm {
  username: string
  password: string
  rememberMe?: boolean
}

export interface RegisterForm {
  username: string
  email: string
  password: string
  confirmPassword: string
  agreeTerms: boolean
}

// 模拟API调用延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string | null>(null)
  const loading = ref(false)

  // 从localStorage恢复用户状态
  const initUserState = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      userInfo.value = JSON.parse(savedUserInfo)
    }
  }

  // 保存用户状态到localStorage
  const saveUserState = () => {
    if (token.value && userInfo.value) {
      localStorage.setItem('token', token.value)
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  // 清除用户状态
  const clearUserState = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    token.value = null
    userInfo.value = null
  }

  // 登录
  const login = async (loginForm: LoginForm) => {
    loading.value = true
    try {
      console.log('发送登录请求:', loginForm)
      const response = await axios.post(`${API_URL}/users/login`, {
        username: loginForm.username,
        password: loginForm.password
      })
      console.log('登录响应:', response.data)
      
      const { token: apiToken, ...userInfoData } = response.data
      token.value = apiToken
      userInfo.value = userInfoData

      if (loginForm.rememberMe) {
        saveUserState()
      }

      return userInfo.value
    } catch (error: any) {
      console.error('登录错误:', error.response?.data || error.message)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerForm: RegisterForm) => {
    loading.value = true
    try {
      console.log('发送注册请求:', registerForm)
      const response = await axios.post(`${API_URL}/users/register`, {
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password
      })
      console.log('注册响应:', response.data)
      
      const { token: apiToken, ...userInfoData } = response.data
      token.value = apiToken
      userInfo.value = userInfoData

      localStorage.setItem('token', apiToken)
      
      return userInfo.value
    } catch (error: any) {
      console.error('注册错误:', error.response?.data || error.message)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    loading.value = true
    try {
      clearUserState()
    } catch (error: any) {
      console.error('登出错误:', error.response?.data || error.message)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    if (!token.value) return null
    
    loading.value = true
    try {
      console.log('获取用户信息')
      const response = await axios.get(`${API_URL}/users/profile/${userInfo.value?.id}`, {
        headers: {
          Authorization: `Bearer ${token.value}`
        }
      })
      console.log('用户信息响应:', response.data)
      
      userInfo.value = {
        id: response.data._id,
        username: response.data.username,
        email: response.data.email,
        role: response.data.role,
        avatar: response.data.avatar
      }
      
      return userInfo.value
    } catch (error: any) {
      console.error('获取用户信息错误:', error.response?.data || error.message)
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    userInfo,
    token,
    loading,
    login,
    register,
    logout,
    getUserInfo,
    initUserState
  }
}, {
  persist: true
}) 